﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ELab.Client;
using ELab.Serialization.Data;
using ELab.Communication.Messages.ControllerMessages;
using System.Threading;

namespace ELab.Teacher.Controls
{
    public partial class ctrlCreationQuestion : UserControl
    {
        public ctrlCreationQuestion()
        {
            InitializeComponent();
        }

        public ELabClient TeacherControl { get; set; }
        public IEnumerable<User> Users { get; set; }

        private void ctrlCreationQuestion_Load(object sender, EventArgs e)
        {
            lbMessage.Text = "";
            AddAnswer(4);
        }
        private void btnAddAnswer_Click(object sender, EventArgs e)
        {
            AddAnswer(1);
        }
        private void AddAnswer(int number)
        {
            for (int i = 0; i < number; i++)
            {
                pnAnswers.Controls.Add(new ctrlAnswer());
            }
            pnAnswers.Refresh();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
        }
        private void ClearForm()
        {
            txtQuestion.Text = string.Empty;
            pnAnswers.Controls.Clear();
            AddAnswer(4);
        }


        private void btnSaveAndContinue_Click(object sender, EventArgs e)
        {
            string message = SaveQuestionAnswer();
            ClearForm();
            lbMessage.Text = message;
        }

        private void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            string message = SaveQuestionAnswer();
            lbMessage.Text = message;

            Thread.Sleep(500);
            ctrlQAManagement parent = (ctrlQAManagement)this.Parent.Parent;
            parent.RaiseCancel();
        }

        private string SaveQuestionAnswer()
        {
            Question q = new Question();
            q.QuestionValue = txtQuestion.Text;
           var answers = new List<Answer>();
           foreach (ctrlAnswer answer in pnAnswers.Controls)
           {
               answers.Add(answer.GetAnswer());
           }
           q.Answers = answers.ToArray();
            // Save Question to server
            var userListMessage = (GeneralResponseMessage)TeacherControl.Controller.SendMessageAndGetResponse(new AddNewQuestionMessage { Question = q });
            if (userListMessage.IsSuccess) return "The Question/Answers has been saved.";
            else return "Could not get response from server. Please contact with administrator to resolve.";
        }

    }
}
